package elitech.vietnam.myfashion.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Comment;
import elitech.vietnam.myfashion.entites.Product;

public class FooterDetailView extends LinearLayout {
	
	private MainActivity mContext;
	private Product mProduct;
	private TextView mTxtNumberComment;
	private LinearLayout mLayoutComments;
	
	public FooterDetailView(MainActivity context, Product product) {
		super(context);
		this.mContext = context;
		this.mProduct = product;
		
		LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if(inflater != null){
            inflater.inflate(R.layout.footerdetail, this);
        }
		
		
		mTxtNumberComment = (TextView) findViewById(R.id.detail_txtNumberComment);
		mLayoutComments = (LinearLayout) findViewById(R.id.detail_layoutComment);
		
		mTxtNumberComment.setText(mProduct.Comments + "");
		
		GetComment();
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				RefreshComment();
			}
		}, 15000, 15000);
		
	}
	
	private void GetComment() {
		new CallServiceTask() {
			private ArrayList<Comment> rs = new ArrayList<Comment>();

			public void work() {
				try {
					rs = service.getCommentOfProduct(mProduct.Id, 1);
				} catch (IOException e) {
				} catch (XmlPullParserException e) {
				}
			};

			protected void onPostExecute(Void result) {
				mProduct.Comments = rs.size();
				mTxtNumberComment.setText(mProduct.Comments + "");
				for (int i = mLayoutComments.getChildCount(); i < rs.size(); i++) {
					CommentView comment = new CommentView(mContext, rs.get(i));
					mLayoutComments.addView(comment);
				}
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	public void RefreshComment() {
		new CallServiceTask() {
			private ArrayList<Comment> rs = new ArrayList<Comment>();

			public void work() {
				try {
					rs = service.getCommentOfProduct(mProduct.Id, 1);
				} catch (IOException e) {
				} catch (XmlPullParserException e) {
				}
			};

			protected void onPostExecute(Void result) {
				mProduct.Comments = rs.size();
				mTxtNumberComment.setText(mProduct.Comments + "");
				for (int i = mLayoutComments.getChildCount(); i < rs.size(); i++) {
					CommentView comment = new CommentView(mContext, rs.get(i));
					mLayoutComments.addView(comment);
				}
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}
	
}
